//
//  OL_ViewController.m
//  YUXiu
//
//  Created by 王竞成 on 16/6/22.
//  Copyright © 2016年 Wang. All rights reserved.
//

#import "OL_ViewController.h"
#import "OL_View.h"
#import "courseModel.h"
#import "PlayImgCollectionViewCell.h"
#import "MyLayout.h"
#import "OL_SearchViewController.h"

#import "HomeMDCell.h"
#import "PersonInfoViewController.h"
#import "KRVideoPlayerViewController.h"

@interface OL_ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    NSArray *topTitleArray;
    UIView *topView;
    NSMutableArray *advArray;
    UIButton *navRightBtn;
    UICollectionView *collectView;
    NSTimer *scrolTimer;
    UITableView *table1;
    NSArray *cellectionfalseData;


}
@property (nonatomic,strong)UIScrollView *scrollView;   //广告
@property (nonatomic,strong)UIPageControl *pageControl;   //广告分页


@property (retain, nonatomic) UIButton *lastSelectedBtn;//上一个选中按钮
@property (retain, nonatomic) UILabel *selectedLabel;//下划线
@property (nonatomic, strong) UIScrollView *dateScrollView;

@end
#define kCount 3
#define GetPackagesList @"comboController/findComboInfo.do"
#define kBaseServerUrl   @"http://120.25.152.245:9080/golfUp/communityController/findCommunityList.do"

@implementation OL_ViewController

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    scrolTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [scrolTimer invalidate];
    scrolTimer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dateScrollView.scrollEnabled = YES;
    _dateScrollView.clipsToBounds  = NO;
    [_dateScrollView setCanCancelContentTouches:NO];
    _dateScrollView.backgroundColor = [UIColor whiteColor];
    _dateScrollView.contentSize  = CGSizeMake(kScreenWidth, 44);//已接受 320 * count
    
    NSString *url = kBaseServerUrl;
    NSMutableDictionary *paramDic = @{}.mutableCopy;
    [paramDic setValue:@"13ad5274aabf4ba5af53981098cea7d7" forKey:@"appUserId"];
    [paramDic setValue:@"0" forKey:@"pageLabel"];
    [paramDic setValue:@"1" forKey:@"offset"];
    [paramDic setValue:@"20" forKey:@"numPerPage"];
    [paramDic setValue:@"2" forKey:@"ctype"];
    [paramDic setValue:@"4" forKey:@"postType"];
    
    [OL_ViewController requestWithURL:url params:paramDic httpMethod:@"POST" block:^(NSObject *result) {
        
        NSLog(@"obj:%@",result);
    }];
    self.view.backgroundColor = kNaviBarCOLOR;
}
#pragma mark - UI
-(void)autoConfigViews{
    [self.navigationController.navigationBar setTranslucent:NO];
    cellectionfalseData = @[@"历史1",@"历史1",@"历史1",@"历史1",@"历史1"];
    topTitleArray = @[@"推荐",@"待定1",@"待定2",@"待定3"];
    self.tableView.tableHeaderView = [self addAdvertisement];
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:[self initheaderview:topTitleArray]];
    //选中时显示的下划线 kwidth/4,
    float kwd = kScreenWidth/4;
    _selectedLabel = [[UILabel alloc]initWithFrame:CGRectMake(kwd/4, 44 - 1.5, kwd/2, 1.5)];

    _selectedLabel.backgroundColor = kOrangeCOLOR;
    [self.view addSubview:_selectedLabel];
    [self setNaviSubViews];
    
    table1 = [[UITableView alloc]initWithFrame:krect(10, 44, kScreenWidth-20, kScreenHeight-44)];
    table1.separatorStyle = UITableViewCellSelectionStyleNone;
    table1.delegate = self;
    table1.dataSource = self;
    [self.view addSubview:table1];
    [table1 setHidden:YES];
}

-(void)setNaviSubViews{
    navRightBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    navRightBtn.tag = 3001;
    [navRightBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [navRightBtn setImage:[UIImage imageNamed:@"package_nav_icn_search_normal"] forState:0];
    navRightBtn.frame = krect(0, 0, 40, 30);
    navRightBtn.titleLabel.font = Font(13);
    UIBarButtonItem *rightbtnItem = [[UIBarButtonItem alloc]initWithCustomView:navRightBtn];
    [self.navigationItem setRightBarButtonItem:rightbtnItem];
}
//topView
- (UIView *)initheaderview:(NSArray *)mArray{
    UIView *topS = [[UIView alloc]initWithFrame:krect(0, 0, kScreenWidth, 44)];
    topS.backgroundColor = kWhiteCOLOR;
    for (int i = 0; i <mArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(kScreenWidth/4*i+1, 0, kScreenWidth/4-3, 44);
        button.tag = 1001+i;
        [button setTitleColor:kBlackCOLOR forState:UIControlStateNormal];
        [button setTitleColor:kOrangeCOLOR forState:UIControlStateSelected];
        [button setTitle:mArray[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize: 13.0];
        [button addTarget:self action:@selector(fetchDataFromNetWork:) forControlEvents:UIControlEventTouchUpInside];
        [topS addSubview:button];
        
        if (i == 0) {
            button.selected = YES;
            _lastSelectedBtn = button;
        }
    }
    return topS;
}
//table 主头(放置广告滑动视图)
-(UIView *)addAdvertisement{
    //按钮宽度
    UIView *headerview = [[UIView alloc]initWithFrame:krect(0, 0, kScreenWidth, 140+18)];
    _scrollView = [[UIScrollView alloc]initWithFrame:krect(0, 0, kScreenWidth, 140)];
    _scrollView.contentSize = CGSizeMake((kCount + 1)* kScreenWidth, 140);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    
    pageControl.frame = CGRectMake(kScreenWidth - 160, 110, 150, 30);
    
    pageControl.numberOfPages = kCount; // 一共显示多少个圆点（多少页）
    // 设置非选中页的圆点颜色
    pageControl.pageIndicatorTintColor = kColorRGB(62, 163, 255);
    // 设置选中页的圆点颜色
    pageControl.currentPageIndicatorTintColor = kOrangeCOLOR;
    
    
    // 禁止默认的点击功能
    pageControl.enabled = NO;
    _pageControl = pageControl;
    
        if (kCount != 0) {
        for (int i = 0; i < kCount; i ++) {
//            advModel = advArray[i];
            
            UIImageView *img = [[UIImageView alloc]initWithFrame:krect(i * kScreenWidth, 0, kScreenWidth, 140)];
            UIButton *btn = [[UIButton alloc]initWithFrame:krect(i * kScreenWidth, 0, kScreenWidth, 140)];
            [btn addTarget:self action:@selector(ScrollViewclickToWeb:) forControlEvents:UIControlEventTouchUpInside];
            btn.backgroundColor = [UIColor clearColor];
            [img sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"nopoto160x200"]];
            btn.tag = 100+i;
            [_scrollView addSubview:img];
            [_scrollView addSubview:btn];
        }
    }else{
        UIImageView *img = [[UIImageView alloc]initWithFrame:krect(0, 0, kScreenWidth, 140)];
        [img sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"nopoto160x200"]];
        [_scrollView addSubview:img];
    }
    [headerview addSubview:_scrollView];
    [headerview addSubview:_pageControl];
    
       return headerview;
}

- (void)fetchDataFromNetWork:(UIButton *)sender
{
    if (_lastSelectedBtn == sender) return;
    
    _lastSelectedBtn.selected = NO;
    sender.selected = YES;
    _lastSelectedBtn = sender;
    [UIView animateWithDuration:0.25 animations:^{
        _selectedLabel.frame = (CGRect){{sender.frame.origin.x + kScreenWidth/16, sender.golf_bottom - 1.5}, _selectedLabel.frame.size};
    }];
    if (sender.tag == 1001) {
        [self.tableView setHidden:NO];
        [table1 setHidden:YES];
        return;
    }
    [self.tableView setHidden:YES];
    [table1 setHidden:NO];

//    [self requestData:sender];
}

#pragma mark - touch Click
//点击scroView
- (void)ScrollViewclickToWeb:(UIButton*)scrollBtn {
    //滑动视图点击跳转
    
}
-(void)TapUserHeader:(UITapGestureRecognizer *) ges {
    NSInteger num;
    num = ges.view.tag;
    PersonInfoViewController *goVC = [[PersonInfoViewController alloc]init];
    [self.navigationController pushViewController:goVC animated:YES];

}
-(void)btnClick:(UIButton *)btn {
    if( btn.tag == 3001){
//        搜索按钮
        OL_SearchViewController *goVC = [[OL_SearchViewController alloc]init];
        

        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
        
        
        [self.navigationController pushViewController:goVC animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - scrollview Delegate
- (void)runTimePage
{   //计时器方法
    int page = _scrollView.contentOffset.x/kScreenWidth;// 获取当前的page
    page++;
//    page = page>advArray.count-1 ? 0 : page;
    page = page>3-1 ? 0 : page;

    [_pageControl setCurrentPage:page];
    [_scrollView scrollRectToVisible:CGRectMake(page*kScreenWidth, 0, kScreenWidth, 200) animated:NO];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int i = scrollView.contentOffset.x/kScreenWidth;
    [_pageControl setCurrentPage:i];
    //停止计时器,避免scrllView滑动过后Timer效果接着滑动
    [scrolTimer setFireDate:[NSDate distantFuture]];
    [self performSelector:@selector(reStartTimer) withObject:nil afterDelay:3];
}
-(void)reStartTimer{
    //重启计时器
    [scrolTimer setFireDate:[NSDate distantPast] ];
}
#pragma mark - tableView delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(tableView == table1) return 2;

    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView)     return 90;
    else return 0;
        
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView)   return (cellectionfalseData.count/2 +cellectionfalseData.count%2)*140;
    else return 240;

}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView == table1) {
        return 10;
    }
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:krect(0, 0, kScreenWidth, 10)];
    view.backgroundColor = kNaviBarCOLOR;
    return view;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        UIView *hdSection = [[UIView alloc]initWithFrame:krect(0, 0, kScreenWidth, 90)];
        for (int i = 0; i<5; i++) {
            UIView *tempView = [[UIView alloc]initWithFrame:krect(kScreenWidth/5*i, 0, kScreenWidth/5, 60)];
            [hdSection addSubview:tempView];
            UIImageView *img = [[UIImageView alloc]initWithFrame:krect((kScreenWidth/5 -60)/2, 0, 60, 60)];
            [tempView addSubview:img];
            img.layer.cornerRadius = 27;
            img.layer.masksToBounds = YES;
            img.userInteractionEnabled = YES;
            [img setImage:[UIImage imageNamed:@"001.jpg"]];
            img.tag = 20 +i;
            // //待加手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self  action:@selector(TapUserHeader:)];
            [img addGestureRecognizer:tap];
            
        }
        UIView *line = [[UIView alloc]initWithFrame:krect(0, 80, kScreenWidth, 10)];
        line.backgroundColor = kLightGrayCOLOR;
        [hdSection addSubview:line];
        return hdSection;

    }
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        static NSString *identy = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identy];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identy];
        }
        MyLayout *layout = [[MyLayout alloc]init];
        collectView = [[UICollectionView alloc]initWithFrame:krect(0, 0, kScreenWidth, (cellectionfalseData.count/2 +cellectionfalseData.count%2)*140) collectionViewLayout:layout];
        collectView.delegate = self;
        collectView.dataSource = self;
        collectView.backgroundColor = kWhiteCOLOR;
        collectView.scrollEnabled = NO;
        [cell.contentView addSubview:collectView];
        
        [collectView registerClass:[PlayImgCollectionViewCell class] forCellWithReuseIdentifier:@"MyCell"];
        
        return cell;

    }else{
        HomeMDCell *cell = [[HomeMDCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell3"];
        cell.block = ^{
            NSLog(@"点了头像按钮 ");
            PersonInfoViewController *goVC = [[PersonInfoViewController alloc]init];

            [self.navigationController pushViewController:goVC animated:YES];
        };
        return cell;
        
    }
}

#pragma mark - collectionView delegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return cellectionfalseData.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   PlayImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    
    return cell;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
